<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/
jimport( 'joomla.application.component.view' );

require_once(JPATH_COMPONENT.DS.'asset'.DS.'XMLImportHelper.php');


class JAJobBoardViewJAXMLImport extends JAView
{
	/**
	 * $_id;
	 * 
	 * */
	var $_id;
	/**
	 * $_data;
	 * 
	 * */
	var $_data;
	/**
     * Constructor
     */
    function __construct() {
        parent::__construct( );  
        $this->_id = JRequest::getVar('cid',  0, '', 'array');
		$this->_id = (int)$this->_id[0];      
    }
    /**
     * Display the view
     */
    function display($tmpl = null)
    {
    	$tab = JRequest::getVar("tab", "feeds");
    	$task = JRequest::getVar("task", "list");
    	
    	if($task!='importstatus'){
    	?> 
		 
		 <div style="width: 100%; position: relative;">
		 	<div style="margin-left: 17.5%; border: 1px solid #999999; padding:  4px;">
		 		<img border="0" alt="Tooltip" src="<?php global $mainframe; echo $mainframe->getSiteURL()?>/includes/js/ThemeOffice/warning.png"/>
		 		<?php echo JText::_('XML TOOL NOTICE MESSAGE')?>
		 	</div>
		 
		 </div>
		 <?php
    	}
		
    	
    	switch($tab)
		{			
			case "feeds":{
				switch ($task){					
					case "edit":
					case "add":
						$this->displayAddItems();
						break;
					case "setupstruct":
						$this->displaySetupStruct();
						break;
					case "setupfield":
						$this->displaySetupField();
						break;
					case "importdata":
						$this->displayImportData();
						break;
					case "importstatus":
						$this->displayImportStatus();
						break;
					case "importlog":
						$this->displayImportLog();
						break;
					default:
						$this->displayListItems();
						break;
				}
			}
			break;
			case "imported":{
				switch ($task){
					case "list":
						$this->displayImportedList();
						break;
				}
			}
			break;
		}
		
		parent::display($tmpl);
  	}
  	
  	/**
  	 * Generate selectbox for feed categories
  	 * @param int $selectID selected id
  	 * @return string selectbox in html format
  	 * */
  	
  	function getSelectboxCategory($selectID){
  		$db =& JFactory::getDBO();
		$db->setQuery("SELECT id, title FROM #__ja_feeds_categories");		
		$groups = $db->loadObjectList();
		if( 1 ){ 
			foreach ($groups as $value=>$text){
				$groupHTML[] = JHTML::_('select.option', $text->id, $text->title);  
			}			
			
			$lists = JHTML::_('select.genericlist',   $groupHTML, 'catid', 'class="inputbox" size="1"', 'value', 'text', $selectID);
		}
		return  $lists; 		
  	}
  	
  	/**
  	* Display List of items
  	*/
  	function displayListItems(){  				
		global $mainframe, $option;
		
		// JToolBarHelper::addNewX("add", JText::_("New"));
		// JToolBarHelper::editListX("edit", JText::_("Edit"));
		// JToolBarHelper::deleteListX(JText::_("Are you sure?"), "remove", "Delete");
			
		$model =& $this->getModel();		
		
        $option_1 = $option.'.jaxmlimport';
		$search	= $mainframe->getUserStateFromRequest( "$option_1.search", 'search', 	'',	'string' );
		$lists['search']	= JString::strtolower($search );
				
		$lists['filter_order'] = JRequest::getVar('filter_order', 'u.feed_id');
		$lists['filter_order_Dir']	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$lists['option']	= $option;
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );	
		$lists['state']		= JHTML::_('grid.state',  $filter_state );
		
        // get data items
        $items = $model->getItems();   
		
        $pagination =& $this->get('Pagination');       
        $this->assignRef('lists', $lists);
        $this->assignRef('items', $items);
        $this->assignRef('usergroup', $usergroup);
        $this->assignRef('pagination', $pagination);		
  	}
  	
  	/**
  	 * Display add category form
  	 * */
  	function displayAddCategories(){
  		if(JRequest::getVar("task") == "add"){
  			JToolBarHelper::save();
  			JToolBarHelper::cancel();
  		}
  		$model =& $this->getModel();
  		$this->assignRef("data", $model->getCategoryItem());
  	}
  	
  	/**
  	 * Display add item form
  	 * */
  	function displayAddItems(){  		
  		$model =& $this->getModel();
  		$this->assignRef("data", $model->getFeedItem());
  	}
  	
  	/**
  	 * Display setup for XML struct
  	 * */
  	function displaySetupStruct(){
  		// Create toolbar  		
  		
  		// Get data
  		$model =& $this->getModel();
  		$feedrow = $model->getFeedItem();
  		
  		// Assign data
  		$this->assignRef("data", $feedrow);
  	}
  	
  	/**
  	 * Display setup field for XML
  	 * */
  	function displaySetupField(){  		
  		require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jajobboard'.DS.'asset'.DS.'rendfield.php');
  		// Get data
  		$model =& $this->getModel();
  		$feedrow = $model->getFeedItem();
  		
  		// Assign data
  		$this->assignRef("data", $feedrow);
  	}
  	
  	/**
  	 * Display import data form
  	 * */
  	function displayImportData(){
  		// Create toolbar
  		
  		
  		// Get data
  		$model =& $this->getModel();
  		$feedrow = $model->getFeedItem();
  		
  		// Assign data
  		$this->assignRef("data", $feedrow);
  	}
  	
  	/**
  	 * Display import data status
  	 * */
  	function displayImportStatus(){
  		
  		// Get data
  		$model =& $this->getModel();
  		$feedrow = $model->getFeedItem();
  		
  		// Assign data
  		$this->assignRef("data", $feedrow);
  		
  	}
  	
  	/**
  	 * Display import data log
  	 * */
  	function displayImportLog(){
  		
  		// Get data
  		$model =& $this->getModel();
  		$feedrow = $model->getFeedItem();
  		
  		// Assign data
  		$this->assignRef("data", $feedrow);
  		
  	}
  	
  	/**
  	* Display List of categories
  	*/
  	function displayImportedList(){  				
		global $mainframe, $option;
		
		$usergroup = JRequest::getVar('usergroup', 'admin');		
			
		$model =& $this->getModel();		
		
        $option_1 = $option.'.jaxmlimport';
		$search	= $mainframe->getUserStateFromRequest( "$option_1.search", 'search', 	'',	'string' );
		$lists['search']	= JString::strtolower($search );
		
		$lists['filter_order'] = JRequest::getVar('filter_order', 'u.ordering');
		$lists['filter_order_Dir']	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$lists['option']	= $option;
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );	
		$lists['state']		= JHTML::_('grid.state',  $filter_state );
		
		$usertype = '';
		$usertype			= $mainframe->getUserStateFromRequest( $option_1.$usergroup.'.usertype', 'usertype', '',	'string' );
					
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT FeedID, FeedName FROM #__ja_xml_import_feeds");		
		$groups = $db->loadObjectList();
		if( 1 ){
			$groupHTML[] = JHTML::_('select.option', '', JText::_('Select XML Feed...'));  
			if (is_array($groups))
				foreach ($groups as $value=>$text){
					$groupHTML[] = JHTML::_('select.option', $text->FeedID, $text->FeedName);  
				}			
			
			$lists['group'] = JHTML::_('select.genericlist',   $groupHTML, 'usertype', 'class="inputbox" size="1" onchange="form.submit()"', 'value', 'text', $usertype);
		}
		
        // get data items
        $items = $model->getImported();
		
        $pagination =& $this->get('Pagination');       
        $this->assignRef('lists', $lists);
        $this->assignRef('items', $items);
        $this->assignRef('usergroup', $usergroup);
        $this->assignRef('pagination', $pagination);		
  	}  	
	
  	/**
	 * Get system user and fill to selectbox
	 * */
	function getSystemUsers($selectID){
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT id, name, username FROM #__users WHERE usertype = 'Super Administrator' OR params like '%usertype=Employer User%' ");
		$groups = $db->loadObjectList();
		$groupHTML[] = JHTML::_('select.option', "", "[Select user]");
		foreach ($groups as $value=>$text){
			$groupHTML[] = JHTML::_('select.option', $text->username, $text->name." >> ".$text->username);
		}
			
		$lists = JHTML::_('select.genericlist', $groupHTML, 'default_user', 'class="inputbox"', 'value', 'text', $selectID);
		
		return $lists;
	}
	
	/**
	 * Get validate combobox
	 * */
	function getValidateOptions($name, $selectID){
		
		$groupHTML = array();
		$groupHTML[] = JHTML::_('select.option', "", "No validation needed");  
		$groupHTML[] = JHTML::_('select.option', "not_blank", "Not blank");
		$groupHTML[] = JHTML::_('select.option', "alphanumeric", "Alphanumeric");
		$groupHTML[] = JHTML::_('select.option', "numeric", "Numeric");
		$groupHTML[] = JHTML::_('select.option', "email", "Email");
		$groupHTML[] = JHTML::_('select.option', "currency", "Currency");
		$groupHTML[] = JHTML::_('select.option', "url", "URL");
					
		$lists = JHTML::_('select.genericlist', $groupHTML, $name, 'class="inputbox"', 'value', 'text', $selectID);
		
		return $lists;
	}
	
	/**
	 * Get selectbox data in html string
	 * @param string $name Name of combobox
	 * @param int $id Value of option tag
	 * @param string $value Text in option tag
	 * @param int $selectID Value of selected option tag
	 * @return string $lists hmtl string present combobox.
	 * */
	function getComboboxData($row, $name, $table, $key, $value, $selectID, $multilevel=false, $parentText="--Root--"){
		$db =& JFactory::getDBO();
		
		if($table == "#__"){
			$table 	= "#__ja_codes";
			$key 	= "value";
			$value 	= "text";
			$conditon = "field_id = '".$row->table_name."_".$row->field_name."'";
		}
		
		if($table!='#__ja_categories' && $table!='#__ja_location')
			$db->setQuery("SELECT $key, $value FROM {$table} WHERE $conditon ORDER BY $value ASC");
		else
			$db->setQuery("SELECT $key, $value FROM {$table} WHERE parent_id = '0' ORDER BY $value ASC");
		
		$groups = $db->loadAssocList();
		
		if($parentText != '' && $table != "#__ja_codes" )
			$groupHTML[] = JHTML::_('select.option', "0", $parentText);
		
		foreach ($groups as $k1=>$text){			
			$groupHTML[] = JHTML::_('select.option', $text[$key], "&nbsp;&nbsp;&nbsp;".$text[$value]);  
			if($multilevel && ($table=='#__ja_categories' || $table=='#__ja_location' )){
				$db->setQuery("SELECT $key, $value FROM {$table} WHERE parent_id = '{$text[$key]}' ORDER BY $value ASC");
				$groups1 = $db->loadAssocList();
				foreach ($groups1 as $k2=>$text1){
					$groupHTML[] = JHTML::_('select.option', $text1[$key], "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$text1[$value]);
				}
			}
		}
		
		$lists = JHTML::_('select.genericlist', $groupHTML, $name, 'class="inputbox"', 'value', 'text', $selectID);
		
		return $lists;
	}
	
	/**
	 * Get selectbox data in html string
	 * @param string $name Name of combobox
	 * @param int $id Value of option tag
	 * @param string $value Text in option tag
	 * @param int $selectID Value of selected option tag
	 * @return string $lists hmtl string present combobox.
	 * */
	function getComboboxDataCode($name, $codition, $selectID){
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT value, text FROM #__ja_codes WHERE field_id = '{$codition}' ORDER BY value ASC");
		$groups = $db->loadObjectList();
		foreach ($groups as $value=>$text){
			$groupHTML[] = JHTML::_('select.option', $text->value, $text->text);
		}
		
		$lists = JHTML::_('select.genericlist', $groupHTML, $name, 'class="inputbox"', 'value', 'text', $selectID);
		
		return $lists;
	}
  	
	function menu_User()
	{
		global $option;
		
		$tab = JRequest::getVar('tab','feeds');
		
		?>
			<div class="t">
				<div class="t">
					<div class="t"></div>
				</div>
			</div>
			<div class="m">
				<ul id="submenu">
					<li>
						<a href="index.php?option=<?php echo $option; ?>&view=jaxmlimport&tab=feeds" class="<?php if($tab==null||$tab=='feeds')echo 'active' ?>">
							<?php echo JText::_( 'XML FEED SETUP' ); ?>
						</a>
					</li>				
					<li>			
							<a href="index.php?option=<?php echo $option; ?>&view=jaxmlimport&tab=logs" class="<?php if($tab=='logs')echo 'active' ?>" >
								<?php echo JText::_( 'XML IMPORT LOG' ); ?>
							</a>
					</li>	
					<li>			
							<a href="index.php?option=<?php echo $option; ?>&view=jaxmlimport&tab=imported" class="<?php if($tab=='imported')echo 'active' ?>" >
								<?php echo JText::_( 'IMPORTED JOBS' ); ?>
							</a>
					</li>		
				</ul>
				<div class="clr"></div>
			</div>
			<div class="b">
				<div class="b">
					<div class="b"></div>
				</div>
			</div>		
		<?php		
	}
}


/*
	Build HTML Tree From XML file
*/

class buildXMLStruct {

    // Variables
    var $parser;
    var $name;
    var $attr;
    var $keys;
    var $path;
	var $line;
	var $startName;
	var $depth;
	var $keyStack;
	var $data  = array();
    var $stack = array();
	var $popKey;
	var $pushKey;
	
	// XML string
    var $xml_strings = array();
    
    var $seq;
    	
    // Constructor
    function buildXMLStruct($strXML, $seq) {
    	$this->seq = $seq;		
		$strXML = str_replace("&", "&amp;", $strXML);
        $this->xml_strings = explode("\n", $strXML);
        $this->url  = "";
		$this->line = 0;
		$this->depth = 0;
        $this->parse();	
        echo $this->seq;
    }
  
    // parse XML data
    function parse(){
        $data = '';
        $this->parser = xml_parser_create ("UTF-8");
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
		$lineCount = sizeof($this->xml_strings);
		$i=0;
		$lastLine=false;
		foreach ($this->xml_strings as $line) {
			if ($lineCount==$i) {
				$lastLine = true;
			}
			if (!xml_parse($this->parser, $line, $lastLine)) {
				$this->error(sprintf('XML error at line %d column %d',
				xml_get_current_line_number($this->parser),
				xml_get_current_column_number($this->parser)));
			}
			$i++;
		}
    }

    function startXML($parser, $name, $attr)    {
		$this->depth++;
		$this->start_name	= $name;
		$this->key_stack[] 	= $name; // push name on the stack
		$this->pushed_key 	= $name;
		echo "<br>\n";
		for ($i=0; $i<$this->depth; $i++) {
			echo '<span class="XMLelement">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
		}
        $this->stack[$name] = array();
        $keys 	= '';
        $total 	= count($this->stack)-1;
        $i		=0;
        foreach ($this->stack as $key => $val)    {
            if (count($this->stack) > 1) {
                if ($total == $i)
                    $keys .= $key;
                else
                    $keys .= $key . '|'; // The saparator
            }
            else
                $keys .= $key;
            $i++;
        }
		$my_key_stack = $this->key_stack;
		$i		= 0;
		$pipe 	= '';
		$key_str = "";
		for ($i=0; $i < sizeof($this->key_stack); $i++) {
			$key_str .= $pipe.array_shift($my_key_stack);
			$pipe = '|';
		}	
		?>
			<input type="radio" <?php if($this->seq == $key_str) echo 'checked="checked"'; ?>  name="element" value="<?php echo $key_str;?>" onclick="javascript:selectSeqElement('<?php echo $name.$this->depth;?>')" >
		<?php
		echo "<div style='display:inline'   ><span id='".$name.$this->depth."' class='XMLelement'>&lt;$name&gt;</span>";
		echo '<font color="#0000FF">'.$key_str.'</font>';
		if($key_str == $this->seq)
			$this->seq = '<script language="javascript">selectSeqElement("'.$name.$this->depth.'");</script>';
		$this->data[$keys]['attr'] = $attr;
        $this->keys = $keys;
    }

    function endXML($parser, $name){
		$this->popped_key = array_pop($this->key_stack);
		if (key($this->stack)!= '' ) {
			echo "<br>\n";
			for ($i=0; $i<$this->depth; $i++) {
				echo '<span class="XMLelement">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></div>';
			}
		}
		end($this->stack);
		echo "<span id='".$name.$this->depth."_end' class='XMLelement'>&lt;/$name&gt;</span>";
		if ($this->start_name == $name)
        if (key($this->stack) == $name)
            array_pop($this->stack);
		$this->depth--;
    }

    function charXML($parser, $data){			
        if (trim($data) != '')        
			$this->data[$this->keys]['data'][] = trim(str_replace("\n", '', $data));			
    }

    function error($msg){
        echo "<div align=\"center\">
            <font color=\"red\"><b>Error: $msg</b></font>
            </div>";
        exit();
    }	
}

?>